/* MAKEPAK.C
 * Pakfile creation utility
 *************
 * 29.08.2000 : Toni R„s„nen
 *              modifications/documentation for open source
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include "mpack.h"
#include "gfx2.h"
#include "version.h"
#include "pakfile.h"

typedef struct {  char name[13] PACKED;
                  int fpos PACKED;
                  int flength PACKED;
               }  filelisttype PACKED;

char pakidtag[16] = { 'I', 'P', 'K', 'G', 8,8,8,8, 'K','G','B','I', 0,0,0,0 };

filelisttype files[64];
int filec;

int i,o;

char rivi[50];
FILE *tied;


char *temp;

void read_listfile(char *name)
{  strcpy (rivi, name);
   strcat (rivi, ".pls");
   tied = fopen (rivi, "r");

   filec = 0;
   printf ("Reading list: %s...\n",name);
   while (!feof(tied))
     {  fgets (rivi, 80, tied);
          // remove last CR and padding spaces
        while (rivi[strlen(rivi)-1] == 10) rivi[strlen(rivi)-1] = 0;
        while (rivi[0] == ' ') strcpy (rivi, rivi+1);
        if ( (rivi[0] != ';') && (rivi[0] != 0) )
          {  strcpy (files[filec].name, rivi);
             filec++;
          }
     }

   printf ("%i files... Verifying integrity...\n", filec);
   for (i = 0; i < filec; i++)
     {  tied = fopen (files[i].name, "rb");
        if (tied == NULL)
          {  printf ("ERROR: File [%s] not found!\n", files[i].name);  }
        else
          {  fseek (tied, 0, SEEK_END);
             files[i].flength = ftell (tied);
             fclose (tied);
          }
     }

   o = sizeof(filelisttype) * filec + 20;
   printf ("Files checked... Creating offset list...\n");
   for (i = 0; i < filec; i++)
     {  files[i].fpos = o;
        printf ("%12s %6i %i\n",files[i].name, files[i].fpos, files[i].flength);

        o += (files[i].flength+4); // 4extra bytes, all 0
     }

   fclose (tied);
   
}

void make_pakfile (char *name)
{  FILE *src;
   int n;
   char rivi[20];

   printf ("Creating package...\n");
   strcpy (rivi, name);
   strcat (rivi, ".pkg");
   tied = fopen (rivi, "wb");

   fwrite (pakidtag, 12,1, tied);
   n = PAKFILE_VERSION;
   fwrite (&n, 4,1, tied);

/*   memset (rivi,0,20);
   strcpy (rivi, GAME_VERSION_STR);
   n = strlen(rivi);
   fwrite ( &n, 4,1, tied);
   fwrite (rivi, n,1, tied); */
   
   fwrite (&filec, 4,1, tied);
   fwrite (&files, sizeof(filelisttype)*filec, 1, tied);

   for (i = 0; i < filec; i++)
     {  src = fopen (files[i].name, "rb");
        fread (temp, files[i].flength,1, src);
        fclose (src);

        fwrite (temp, files[i].flength,1, tied);
        n = 0; fwrite (&n, 4,1, tied);        
     }

   printf ("Done.\n");

   fclose (tied);
}

int main ()
{  temp = (char*) malloc (1024*1024); // alloc a meg...

   read_listfile("gameg");
   make_pakfile ("gameg");
}
